<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2022-10-07
 * Time: 19:38
 */

namespace App\controller\baidu;
use support\exception\Forbidden;
use support\Request;
use GuzzleHttp\Client;
use think\facade\Cache;

class Auth
{
    public function index(Request $request)
    {
        if( empty($request->get('code'))){
            throw new Forbidden('没有传入code');
        }
        $arr = [
            'grant_type' => 'authorization_code',
            'code' => $request->get('code'),
            'client_id' => 'QF8ctol3Hb18XM06R53LjfaXw9GoHVMF',
            'client_secret'=>'6iXlQ9t9gDyjoyHTWiGdaWevyGjmHmXq',
            'redirect_uri'=>'https://webman.wyx2013.cn/baidu/auth'
        ];
        $url='https://openapi.baidu.com/oauth/2.0/token?';
        $client = new Client();
        $url=$url.http_build_query($arr);
        $response = $client->get($url);
        if($response->getStatusCode()===200){
            $arr=json_decode($response->getBody(),true);
        }
        $state=$request->get('state');
        Cache::set('baidu'.$state,$arr,2592000);
        return json(['code'=>0,$arr]);
    }
}